<template>
  <div class="min-h-screen flex flex-col bg-gray-100">
    <!-- 顶部导航 -->
    <header class="bg-white shadow-sm">
      <div class="px-4 h-14 flex items-center justify-between">
        <h1 class="text-lg font-bold">工厂管理系统</h1>
        <el-dropdown @command="handleCommand">
          <span class="flex items-center cursor-pointer">
            <el-avatar 
              :size="32" 
              :src="avatarUrl" 
              :alt="userInfo.username"
              @error="handleAvatarError"
            >
              {{ userInfo.username ? userInfo.username.charAt(0).toUpperCase() : 'U' }}
            </el-avatar>
            <span class="ml-2">{{ userInfo.username || '加载中...' }}</span>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </header>

    <!-- 主要内容区 -->
    <main class="flex-1 overflow-auto pb-14">
      <router-view></router-view>
    </main>

    <!-- 底部导航栏 -->
    <nav class="fixed bottom-0 left-0 right-0 bg-white border-t">
      <div class="grid grid-cols-4 h-14">
        <router-link 
          to="/" 
          class="flex flex-col items-center justify-center"
          :class="{ 'text-primary': $route.path === '/' }"
        >
          <el-icon><HomeFilled /></el-icon>
          <span class="text-xs mt-1">主页</span>
        </router-link>

        <router-link 
          to="/work-items" 
          class="flex flex-col items-center justify-center"
          active-class="text-primary"
        >
          <el-icon><Box /></el-icon>
          <span class="text-xs mt-1">工件</span>
        </router-link>

        <router-link 
          to="/employees" 
          class="flex flex-col items-center justify-center"
          active-class="text-primary"
        >
          <el-icon><User /></el-icon>
          <span class="text-xs mt-1">员工</span>
        </router-link>

        <router-link 
          to="/other" 
          class="flex flex-col items-center justify-center"
          active-class="text-primary"
        >
          <el-icon><More /></el-icon>
          <span class="text-xs mt-1">其他</span>
        </router-link>
      </div>
    </nav>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { HomeFilled, Box, User, More } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserInfo, logout } from '../api/auth'

const router = useRouter()
const userInfo = ref({
  username: '',
  role: '',
  avatarHash: ''  // 添加 avatarHash 字段
})

// 获取头像 URL
const avatarUrl = computed(() => {
  const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'
  return userInfo.value.avatarHash 
    ? `${baseUrl}/api/avatar/${userInfo.value.avatarHash}`
    : ''
})

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const res = await getUserInfo()
    if (res.code === 200 && res.data) {
      userInfo.value = {
        username: res.data.username || '',
        role: res.data.role || '',
        avatarHash: res.data.avatarHash || ''  // 保存 avatarHash
      }
      console.log('用户信息:', res.data)
    } else {
      throw new Error(res.message || '获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error(error.message || '获取用户信息失败')
  }
}

// 处理头像加载错误
const handleAvatarError = () => {
  console.error('头像加载失败')
  userInfo.value.avatarHash = ''  // 清空 avatarHash，将显示默认的文字头像
}

// 处理下拉菜单命令
const handleCommand = async (command) => {
  if (command === 'logout') {
    try {
      await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      await logout()
      localStorage.removeItem('token')
      router.push('/login')
      ElMessage.success('退出登录成功')
    } catch (error) {
      if (error !== 'cancel') {
        console.error('退出登录失败:', error)
      }
    }
  }
}

onMounted(() => {
  fetchUserInfo()
})

// 在组件卸载时清理 URL 对象
onUnmounted(() => {
  if (avatarUrl.value) {
    URL.revokeObjectURL(avatarUrl.value)
  }
})
</script>

<style>
.router-link-active {
  color: inherit;  /* 移除默认的激活样式 */
}

.router-link-exact-active {
  color: var(--el-color-primary);
}

.text-primary {
  color: var(--el-color-primary);
}

.el-avatar {
  background-color: var(--el-color-primary);
  color: white;
}

nav {
  z-index: 100;
  box-shadow: 0 -2px 6px rgba(0, 0, 0, 0.05);
}
</style> 